//
//  RXSwiftExtensions.swift
//  Entrance
//
//  Created by chunhuiLai on 2018/1/15.
//  Copyright © 2018年 chunhuiLai. All rights reserved.
//

import Foundation
import RxSwift

func connectedToInternetOrStubbing() -> Observable<Bool> {
    
    //    let stubbing = Observable.just(APIKeys.sharedKeys.stubResponses)
    //
    //    guard let online = reachabilityManager?.reach else {
    //        return stubbing
    //    }
    //
    //    return [online, stubbing].combineLatestOr()
    
    return Observable.just(true)
}

extension Observable where Element: Equatable {
    func ignore(value: Element) -> Observable<Element> {
        return filter { (e) -> Bool in
            return value != e
        }
    }
}

protocol BooleanType {
    var boolValue: Bool { get }
}
extension Bool: BooleanType {
    var boolValue: Bool { return self }
}

extension Collection where Iterator.Element: ObservableType, Iterator.Element.E: BooleanType {
    
    func combineLatestAnd() -> Observable<Bool> {
        return Observable.combineLatest(self) { bools -> Bool in
            return bools.reduce(true, { (memo, element) in
                return memo && element.boolValue
            })
        }
    }
    
    func combineLatestOr() -> Observable<Bool> {
        return Observable.combineLatest(self) { bools in
            bools.reduce(false, { (memo, element) in
                return memo || element.boolValue
            })
        }
    }
}

//MARK: Logger
extension Observable {
    func logError(prefix: String = "Error: ") -> Observable<Element> {
        return self.do(onError: { error in
            print("\(prefix)\(error)")
        })
    }
    
    func logServerError(message: String) -> Observable<Element> {
        return self.do(onError: { e in
            let error = e as NSError
            defaultLogger.log(message)
            
            defaultLogger.log("Error: \(error.localizedDescription). \n \(error.artsyServerError())")
        })
    }
    
    func logNext() -> Observable<Element> {
        return self.do(onNext: { element in
            print("\(element)")
        })
    }
}

